package net.huashitong.Indicators.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Indicators.entity.UserInfo;
import net.huashitong.Indicators.filter.UserInfoFilter;
import net.huashitong.Indicators.service.UserInfoService;
import net.huashitong.until.Until;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//1.插入用户、2.更新用户、3.插入权限、4.更新权限
@Controller
@RequestMapping(value = "/api/userinfo")
public class UserInfoController extends JsonBaseController {

    @Autowired
    private UserInfoService service;
    @Override
    protected String getView(String s) {
        return null;
    }

    //第一次数据接入，先保存用户信息列表(saveusers)，接着保存用户没有权限的指标(savenoright)
    //之后调用，更新用户信息列表(updateusers)，接着更新用户没有权限的指标(updatenoright)
    /**
     * 保存用户信息列表
     */
    @ResponseBody
    @RequestMapping(value = "/saveusers",method = RequestMethod.POST)
    public Message saveUsers(){
        //从第三方获取用户信息
        List<UserInfo> list = service.callBackUsers();
        if(list!=null){
            service.batchSave(list);
            return coverMessage("200", "用户信息列表保存成功");
        }else{
            return coverMessage("200", "用户信息列表保存失败");
        }
    }

    /**
     * 更新用户信息列表
     */
    @ResponseBody
    @RequestMapping(value = "/updateusers",method = RequestMethod.POST)
    public Message updateUsers(){
        //从第三方获取所有用户信息
        List<UserInfo> remoteList = service.callBackUsers();
        //获取本地所有用户信息
        List<UserInfo> localList = service.queryAllUserInfo();
        //本地用户键值对
        Map<String,UserInfo> localUsersMap = new HashMap<>();
        for(UserInfo userInfo : localList){
            localUsersMap.put(userInfo.getUserId(),userInfo);
        }

        List<UserInfo> needUpdateUsers = new ArrayList<>();
        List<UserInfo> needInsertUsers = new ArrayList<>();
        for(UserInfo user : remoteList){
            //如果本地用户表已经存在第三方的用户，则进行更新。否则进行新增
            if(localUsersMap.containsKey(user.getUserId())){
                UserInfo newUserInfo = localUsersMap.get(user.getUserId());
                //更新用户信息
                newUserInfo.setUserId(user.getUserId());
                newUserInfo.setUserName(user.getUserName());
                newUserInfo.setSex(user.getSex());
                newUserInfo.setTel(user.getTel());
                newUserInfo.setDeptCode(user.getDeptCode());
                newUserInfo.setEmail(user.getEmail());
                newUserInfo.setDuty(user.getDuty());
                newUserInfo.setUpdatetime(user.getUpdatetime());
                newUserInfo.setErrCount(user.getErrCount());
                newUserInfo.setUpdateUserid(user.getUpdateUserid());
                newUserInfo.setRoles(user.getRoles());
                needUpdateUsers.add(newUserInfo);
            }else{
                needInsertUsers.add(user);
            }
        }
        //进行批量新增
        service.batchSave(needInsertUsers);
        //进行批量更新
        service.batchUpdate(needUpdateUsers);

        return coverMessage("200", "用户信息列表更新成功");
    }


    /**
     * 保存用户没有权限的指标
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/savenoright",method = RequestMethod.POST)
    public Message saveNoRight(){

//        //需要传token
//        String token = service.getToken();  //获取默认token

        //不需要传token
        //查询所有用户
        List<UserInfo> allUserInfo = service.queryAllUserInfo();
        for(UserInfo userInfo : allUserInfo){
            //不需要传token
            String userId = userInfo.getUserId();
            String url = "userid=" + userId;
            String norights = null;
            try {
                norights = Until.HttpGET(Until.GET_NORIGHTLIST + url, 5000, 5000);
            } catch (IOException e) {
                logger.info("接口: "+ Until.GET_NORIGHTLIST + url);
                e.printStackTrace();
            }

//            //需要传token
//            String userId = userInfo.getUserId();
//            String url = "userid=" + userId+"&token="+token;
//            String norights = Until.HttpGET(Until.GET_NORIGHTLIST_NEED_TOKEN + url, 5000, 5000);

            JSONArray jsonArray = JSONObject.parseArray(norights);
            String noRightResult = jsonArray.toString();
            if(StringUtils.isBlank(noRightResult)){
                noRightResult = "[]";
            }
            userInfo.setNoRight(noRightResult);
            service.update(userInfo);
            System.out.println("保存权限成功");
        }
        return coverMessage("200", "权限插入成功");
    }

    @ResponseBody
    @RequestMapping(value = "/updatenoright",method = RequestMethod.POST)
    public Message updateNoright(){
//        //需要传token
//        String token = service.getToken();  //获取默认token

        //不需要传token

        //从第三方获取所有用户信息
        List<UserInfo> remoteList = service.callBackUsers();

        //查询所有用户
        List<UserInfo> allUserInfo = service.queryAllUserInfo();

        Map<String,String> norightMap = new HashMap<>();

        for(UserInfo userInfo : remoteList){
            //不需要传token
            String userId = userInfo.getUserId();
            String url = "userid=" + userId;
            String norights = null;
            try {
                norights = Until.HttpGET(Until.GET_NORIGHTLIST + url, 5000, 5000);
            } catch (IOException e) {
                logger.info("接口: "+ Until.GET_NORIGHTLIST + url);
                e.printStackTrace();
            }

//            //需要传token
//            String userId = userInfo.getUserId();
//            String url = "userid=" + userId+"&token="+token;
//            String norights = Until.HttpGET(Until.GET_NORIGHTLIST_NEED_TOKEN + url, 5000, 5000);
//            JSONObject jsonObject = JSONObject.parseObject(norights);
//            if("200".equals(jsonObject.getString("returncode"))){
//                String noRightResult = jsonObject.getString("returndata");
//                norightMap.put(userInfo.getUserId(),noRightResult);
//            }else{
//                return coverMessage("500", "获取权限列表失败");
//            }

            String noRightResult = norights;
            if(StringUtils.isBlank(noRightResult)){
                noRightResult = "[]";
            }
            norightMap.put(userInfo.getUserId(),noRightResult);
        }

        List<UserInfo> norightNeedUpdate = new ArrayList<>();
        for(UserInfo u : allUserInfo){
            String userId = u.getUserId();
            if(norightMap.containsKey(userId)){
                u.setNoRight(norightMap.get(userId));
                norightNeedUpdate.add(u);
            }
        }
        service.batchUpdate(norightNeedUpdate);
        return coverMessage("200", "权限更新成功");
    }


    /**
     * 手势验证
     * @param filter openId、ssPwd
     * @return true:通过      false:不通过
     */
    @ResponseBody
    @RequestMapping(value = "/sspwdvalidate",method = RequestMethod.POST)
    public Message ssPwdValidate(@RequestBody UserInfoFilter filter){
        String sysId = filter.getOpenId();      //openId获取用户
        String newSsPwd = filter.getSsPwd();    //新的手势密码
        UserInfo userInfo = service.getById(sysId);     //openId获取用户
        if(userInfo==null){
            return coverMessage("500", "openId出错");
        }
        Map<String,String> res = new HashMap<>();
        //验证手势密码
        if(StringUtils.isNotBlank(userInfo.getSsPwd())){
            if(newSsPwd.equals(userInfo.getSsPwd())){
                return coverMessage("200", "验证完成", true);
            }else{
                return coverMessage("501", "验证不通过", false);
            }
        }else{
            if(StringUtils.isNotBlank(newSsPwd)){
                userInfo.setSsPwd(newSsPwd);
                service.update(userInfo);
                return coverMessage("200", "设置验证完成", true);
            }else{
                return coverMessage("501", "验证不通过", false);
            }
        }
    }
}
